package net.sunofbeaches.controller;

import com.wf.captcha.SpecCaptcha;
import com.wf.captcha.base.Captcha;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;

import net.sunofbeaches.dao.CommentDao;
import net.sunofbeaches.dao.LabelDao;
import net.sunofbeaches.pojo.Comment;
import net.sunofbeaches.pojo.Label;
import net.sunofbeaches.pojo.SobUser;
import net.sunofbeaches.response.ResponseResult;
import net.sunofbeaches.services.IUserService;
import net.sunofbeaches.utils.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.web.bind.annotation.*;


import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Slf4j
@RestController
public class TestController {

    @Autowired
    IdWorker idWorker;
    @Autowired
    LabelDao labelDao;

    @GetMapping("/hello-world")
    public ResponseResult helloWorld() {
        log.info("hello world...");
        String captchaContent = (String) redisUtil.get(Constants.User.KEY_CAPTCHA_CONTENT + "123456");
        log.info("captchaContent == >" + captchaContent);
        return ResponseResult.SUCCESS("成功了").setData("Hello world");
    }

    @GetMapping("/text-json")
    public ResponseResult testJson(@RequestBody SobUser user) {
        log.info("user name == > " + user.getUserName());
        return ResponseResult.SUCCESS().setData(user);
    }

    @PostMapping("/label")
    public ResponseResult addLabel(@RequestBody Label label) {
        //判断数据是否有效
        //补全数据
        label.setId(idWorker.nextId() + "");
        label.setCreateTime(new Date());
        label.setUpdateTime(new Date());
        //保存数据
        labelDao.save(label);
        return ResponseResult.SUCCESS("测试标签添加成功");
    }

    @DeleteMapping("/label/{labelId}")
    public ResponseResult deleteLabel(@PathVariable("labelId") String labelId) {
        int deleteResult = labelDao.customDeleteLabelById(labelId);
        log.info("deleteResult == >" + deleteResult);
        if (deleteResult > 0) {
            return ResponseResult.SUCCESS("删除标签成功");
        } else {
            return ResponseResult.FAILED("标签不存在");
        }
    }

    @PutMapping("/label/{labelId}")
    public ResponseResult updateLabel(@PathVariable("labelId") String labelId
            , @RequestBody Label label) {
        Label dblabel = labelDao.findOneById(labelId);
        if (dblabel == null) {
            return ResponseResult.FAILED("标签不存在");
        }
        dblabel.setCount(label.getCount());
        dblabel.setName(label.getName());
        dblabel.setUpdateTime(new Date());
        labelDao.save(dblabel);
        return ResponseResult.SUCCESS("修改成功");
    }

    @GetMapping("/label/{labelId}")
    public ResponseResult getLabelById(@PathVariable("labelId") String labelId) {
        Label dblabel = labelDao.findOneById(labelId);
        if (dblabel == null) {
            return ResponseResult.FAILED("标签不存在");
        }
        return ResponseResult.SUCCESS("获取标签成功").setData(dblabel);
    }

    @GetMapping("/label/list/{page}/{size}")
    public ResponseResult listLabelS(@PathVariable("page") int page,
                                     @PathVariable("size") int size) {
        if (size < 1) {
            page = 1;
        }
        if (size <= 0) {
            size = Constants.DEFAULT_SIZE;
        }
        List<String> sortProperties = new ArrayList<>();
        sortProperties.add("id");
        sortProperties.add("createTime");
        // 排序 参数一 升序还是降序 排序字段（createTime）不能用字段名称的
        Sort sort = new Sort(Sort.Direction.DESC, sortProperties);
        // 要排序的话 后面需要添加一个参数sort，无排序的话则不需要
        PageRequest pageRequest = PageRequest.of(page - 1, size, sort);
        Page<Label> result = labelDao.findAll(pageRequest);
        return ResponseResult.SUCCESS("获取成功").setData(result);
    }

    @GetMapping("/label/search")
    public ResponseResult doLabelSearch(@RequestParam("keyword") String keyword,
                                        @RequestParam("count") int count) {
        List<Label> all = labelDao.findAll(new Specification<Label>() {
            @Override
            public Predicate toPredicate(Root<Label> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder cb) {
                Predicate namePer = cb.like(root.get("name").as(String.class), "%" + keyword + "%");
                Predicate countPer = cb.equal(root.get("count").as(Integer.class), count);
                Predicate and = cb.and(namePer, countPer);
                return and;
            }
        });
        return ResponseResult.SUCCESS("查找成功").setData(all);
    }

    @Autowired
    private RedisUtil redisUtil;

    @RequestMapping("/captcha")
    public void captcha(HttpServletRequest request, HttpServletResponse response) throws Exception {
        // 设置请求头为输出图片类型
        response.setContentType("image/gif");
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);

        // 三个参数分别为宽、高、位数
        SpecCaptcha specCaptcha = new SpecCaptcha(130, 48, 5);
        // 设置字体
        // specCaptcha.setFont(new Font("Verdana", Font.PLAIN, 32));  // 有默认字体，可以不用设置
        specCaptcha.setFont(Captcha.FONT_1);
        // 设置类型，纯数字、纯字母、字母数字混合
        //specCaptcha.setCharType(Captcha.TYPE_ONLY_NUMBER);
        specCaptcha.setCharType(Captcha.TYPE_DEFAULT);

        String content = specCaptcha.text().toLowerCase();
        // 值
        log.info("captcha content == > " + content);
        // 验证码存入session
        // request.getSession().setAttribute("captcha", content);
        // 保存到redis里,10分钟有效
        redisUtil.set(Constants.User.KEY_CAPTCHA_CONTENT + "123456", content, 60 * 10);

        // 输出图片流
        specCaptcha.out(response.getOutputStream());
    }

    @Autowired
    private CommentDao commentDao;
    @Autowired
    private IUserService userService;

    @PostMapping("/comment")
    public ResponseResult testComment(@RequestBody Comment comment,
                                      HttpServletRequest request,
                                      HttpServletResponse response) {
        String content = comment.getContent();
        log.info("comment content == > " + content);
        // String tokenKey = getCookie(Constants.User.COOKIE_TOKE_KEY, request);
        String tokenKey = CookieUtils.getCookie(request, Constants.User.COOKIE_TOKE_KEY);
        if (tokenKey == null) {
            log.info("tokenKey is null");
            return ResponseResult.FAILED("账号未登录");
        }

        SobUser sobUser = null;
        try {
            sobUser = userService.checkSobUser();
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (sobUser == null) {
            log.info("sobUser => " + sobUser);
            return ResponseResult.FAILED("账号未登录");
        }
        comment.setUserId(sobUser.getId());
        comment.setUserAvatar(sobUser.getAvatar());
        comment.setUserName(sobUser.getUserName());
        comment.setState("1");
        comment.setCreateTime(new Date());
        comment.setUpdateTime(new Date());
        comment.setId(idWorker.nextId() + "");
        commentDao.save(comment);
        return ResponseResult.SUCCESS();
    }
}
